﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static WXTao.WXWindows;

namespace WXTao
{
    public partial class Form1 : Form
    {
        private bool exit_thread = false;
        private WindowInfo[] wx_infos;
        //private WindowInfo[] tb_wx_infos = new WindowInfo[10];
        //private WindowInfo[] jd_wx_infos = new WindowInfo[10];
        //private WindowInfo[] pdd_wx_infos = new WindowInfo[10];

        private List<WindowInfo> tb_wx_infos = new List<WindowInfo>();
        private List<WindowInfo> jd_wx_infos = new List<WindowInfo>();
        private List<WindowInfo> pdd_wx_infos = new List<WindowInfo>();

        Action<String> AsyncUIDelegate;

        public Form1()
        {
            InitializeComponent();
            StartPosition = FormStartPosition.CenterScreen;
            button1.Enabled = false;

            AsyncUIDelegate = delegate (string n) { richTextBox1.Text += n; };
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Weixin weixin = new Weixin(textBox1.Text);
            //weixin.sendContent("500g装秒杀价12.9元", "http://images.cnblogs.com/cnblogs_com/xiohao/429339/o_869851517382210591.png");

            if (button1.Text.Equals("启动"))
            {
                if (tb_wx_infos.Count == 0 && jd_wx_infos.Count==0 && pdd_wx_infos.Count == 0)
                {
                    MessageBox.Show("先加载微信窗口", "提示");
                    return;
                }
                richTextBox1.Text = "";
                exit_thread = false;
                button1.Text = "停止";
                button2.Enabled = false;
                button5.Enabled = false;
                button6.Enabled = false;
                button7.Enabled = false;

                ThreadStart thStart = new ThreadStart(WxPro);//threadStart委托 
                Thread thread = new Thread(thStart);
                thread.SetApartmentState(ApartmentState.STA);
                thread.Priority = ThreadPriority.Highest;
                thread.IsBackground = true; //关闭窗体继续执行
                thread.Start();
            }
            else
            {
                button2.Enabled = true;
                button5.Enabled = true;
                button6.Enabled = true;
                button7.Enabled = true;
                exit_thread = true;
                button1.Text = "启动";
            }
        }

        public void WxPro()
        {
            int cid = 0;
            while (true)
            {
                TimeSpan nowDt = DateTime.Now.TimeOfDay;

                TimeSpan workStartDT = DateTime.Parse("9:00").TimeOfDay;
                TimeSpan workEndDT = DateTime.Parse("23:00").TimeOfDay;
                if (nowDt > workStartDT && nowDt < workEndDT)
                {
                    if (exit_thread)
                        break;
                    if (cid > 3)
                        cid = 0;

                    if (tb_wx_infos.Count > 0)
                        sendTB(cid);

                    if (jd_wx_infos.Count > 0)
                        sendJD();

                    Random ran = new Random();
                    int RandKey = ran.Next(10, 19);
                    for (int i=0;i< RandKey * 60;i++)
                    {
                        if (exit_thread)
                            break;
                        Thread.Sleep(1000);
                    }
                    cid++;
                }
                else
                {
                    Thread.Sleep(60 * 1000);
                }
                
            }
            
        }

        private void sendJD()
        {
            JDTui jd = new JDTui();
            JDData[] datas = jd.getSuggest(jd_wx_infos.Count);
            for (int i = 0; i < jd_wx_infos.Count; i++)
            {
                Weixin weixin = new Weixin(jd_wx_infos[i].szWindowName);
                if (weixin.isWindowExist() && datas.Length > 0)
                {
                    JDData data = datas[i]; ;
                    if (data.ErrorMsg.Equals(""))
                    {
                        string wenan = data.Goods_name+"\n"+ data.Goods_content + "\n【链接】" + data.CouponClickUrl;
                        weixin.sendContent(wenan, "", data.Goods_img);
                        richTextBox1.Invoke(AsyncUIDelegate, 
                            new object[] { "【" + jd_wx_infos[i].szWindowName + " " + DateTime.Now.ToString() + "】" + data.CouponClickUrl + "\n" });
                    }
                    else
                    {
                        richTextBox1.Invoke(AsyncUIDelegate, 
                            new object[] { "【" + jd_wx_infos[i].szWindowName + " " + DateTime.Now.ToString() + "】" + data.ErrorMsg + "\n" });
                    }
                }
                else
                {
                    richTextBox1.Invoke(AsyncUIDelegate, 
                        new object[] { "【提示】" + jd_wx_infos[i].szWindowName + " 微信窗口不存在，点击停止\n" });
                }
            }
            
        }

        private void sendTB(int cid)
        {
            DaTaoKe ke = new DaTaoKe();
            //TBKData[] datas = ke.getSuggest(tb_wx_infos.Count);
            TBKData[] datas = ke.getGoods(tb_wx_infos.Count,cid);
            for (int i = 0; i < tb_wx_infos.Count; i++)
            {
                Weixin weixin = new Weixin(tb_wx_infos[i].szWindowName);
                if (weixin.isWindowExist())
                {
                    TBKData data = datas[i];
                    if (data.ErrorMsg.Equals(""))
                    {
                        if (data.Wenan.Length < 10)
                        {
                            continue;
                        }

                        string wenan = "";

                        if (data.CouponPrice != null && !data.CouponPrice.Equals(""))
                            wenan = data.ActualPrice + "元！\n" + data.Wenan.Replace("&nbsp", "");
                        else
                            wenan = "01" + data.Wenan.Replace("&nbsp", "");

                        string end = "\n【口令】" + data.Tpwd + "/:/";

                        //string kuanzhan = "https://dl028.kuaizhan.com/87/68/p651098661c309d?";
                        //kuanzhan = kuanzhan + "word=" + data.Tpwd.Replace("￥", "").Trim() +
                        //    "&image=" + System.Web.HttpUtility.UrlEncode(data.MarketingMainPic) +
                        //    "&url=" + System.Web.HttpUtility.UrlEncode(data.CouponClickUrl);
                        //string kuanzhan = "https://en80347.kuaizhan.com/64/45/p56946128431779?taowords=";
                        //kuanzhan = kuanzhan + "word=" + data.Tpwd.Replace("￥", "").Trim() +
                        //    "&pic=" + Convert.ToBase64String(Encoding.Default.GetBytes(data.MarketingMainPic));
                        //string kuanzhan = "https://dl030.kuaizhan.com/87/68/p651098661c309d?";
                        //kuanzhan = kuanzhan + "word=" + data.Tpwd.Replace("￥", "").Trim() +
                        //    "&image=" + System.Web.HttpUtility.UrlEncode(data.MarketingMainPic) +
                        //    "&url=" + System.Web.HttpUtility.UrlEncode(data.CouponClickUrl);

                        //string shorturl = shortUrl(kuanzhan);

                        //end += "\n【链接】" + shorturl;
                        end += "\n-------------------\n复制这条消息，打开[手机淘宝]即可领券";

                        weixin.sendContent(wenan, end, data.MarketingMainPic);

                        richTextBox1.Invoke(AsyncUIDelegate, new object[] { "【" + tb_wx_infos[i].szWindowName + " " + DateTime.Now.ToString() + "】" + data.Dtitle + "\n" });

                    }
                    else
                    {
                        richTextBox1.Invoke(AsyncUIDelegate, new object[] { "【" + tb_wx_infos[i].szWindowName + " " + DateTime.Now.ToString() + "】" + data.ErrorMsg + "\n" });
                    }

                }
                else
                {
                    richTextBox1.Invoke(AsyncUIDelegate, new object[] { "【提示】" + tb_wx_infos[i].szWindowName + " 微信窗口不存在，点击停止\n" });
                }
            }
        }

        private string shortUrl(string longurl)
        {
            string api = "http://api.suowo.cn/api.htm?";
            string expireDate = DateTime.Now.AddDays(3).ToString("yyyy-MM-dd");
            
            string param = "url=" + System.Web.HttpUtility.UrlEncode(longurl)+
                "&key=5f5ad82f3a005a216cb4f4e0@bdf7539396b36a63c9f022588c73d5c4&expireDate="+ expireDate;
            using (var client = new HttpClient())
            {
                var responseString = client.GetStringAsync(api+ param);
                return responseString.Result;
            }

        }


        private void button2_Click(object sender, EventArgs e)
        {
            PDD pdd = new PDD();
            richTextBox1.Text = pdd.getGoodsList2();
            //richTextBox1.Text = pdd.getCpsUrl(67925176);
            WXWindows windows = new WXWindows();
            wx_infos = windows.GetAllWXWindows();
            
            if(wx_infos == null || wx_infos.Length == 0)
            {
                button1.Enabled = false;
                return;
            }
            button1.Enabled = true;
            this.listView1.Items.Clear();
            this.listView2.Items.Clear();
            this.listView3.Items.Clear();
            this.listView4.Items.Clear();

            tb_wx_infos.Clear();
            jd_wx_infos.Clear();
            pdd_wx_infos.Clear();


            this.listView1.View = View.List;
            this.listView1.BeginUpdate();
            for (int i = 0; i < wx_infos.Length; i++)
            {
                ListViewItem lvi = new ListViewItem();
                lvi.Text = wx_infos[i].szWindowName;
                this.listView1.Items.Add(lvi);
            }
            this.listView1.EndUpdate();
            
        }


        private void richTextBox1_ClientSizeChanged(object sender, EventArgs e)
        {
            richTextBox1.SelectionStart = richTextBox1.Text.Length;                    //rtbReceive为控件的名字（自己取）
            richTextBox1.ScrollToCaret();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            
        }

        private void button5_Click(object sender, EventArgs e)
        {
            ArrayList al = new ArrayList(wx_infos);
            foreach (ListViewItem lvi in listView1.SelectedItems)  
            {
                tb_wx_infos.Add(wx_infos[lvi.Index]);
                al.RemoveAt(lvi.Index);
                listView1.Items.RemoveAt(lvi.Index); 
            }
            wx_infos = (WindowInfo[])al.ToArray(typeof(WindowInfo));

            this.listView2.View = View.List;
            this.listView2.BeginUpdate();
            for (int i = 0; i < tb_wx_infos.Count; i++)
            {
                if (tb_wx_infos[i].szClassName == null || tb_wx_infos[i].szClassName == "")
                    continue;
                ListViewItem lvi = new ListViewItem();
                lvi.Text = tb_wx_infos[i].szWindowName;
                this.listView2.Items.Add(lvi);
            }
            this.listView2.EndUpdate();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            ArrayList al = new ArrayList(wx_infos);
            foreach (ListViewItem lvi in listView1.SelectedItems)
            {
                jd_wx_infos.Add(wx_infos[lvi.Index]);
                al.RemoveAt(lvi.Index);
                listView1.Items.RemoveAt(lvi.Index);
            }
            wx_infos = (WindowInfo[])al.ToArray(typeof(WindowInfo));

            this.listView3.View = View.List;
            this.listView3.BeginUpdate();
            for (int i = 0; i < jd_wx_infos.Count; i++)
            {
                if (jd_wx_infos[i].szClassName == null || jd_wx_infos[i].szClassName == "")
                    continue;
                ListViewItem lvi = new ListViewItem();
                lvi.Text = jd_wx_infos[i].szWindowName;
                this.listView3.Items.Add(lvi);
            }
            this.listView3.EndUpdate();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            ArrayList al = new ArrayList(wx_infos);
            foreach (ListViewItem lvi in listView1.SelectedItems)
            {
                pdd_wx_infos.Add(wx_infos[lvi.Index]);
                al.RemoveAt(lvi.Index);
                listView1.Items.RemoveAt(lvi.Index);
            }
            wx_infos = (WindowInfo[])al.ToArray(typeof(WindowInfo));

            this.listView4.View = View.List;
            this.listView4.BeginUpdate();
            for (int i = 0; i < jd_wx_infos.Count; i++)
            {
                if (pdd_wx_infos[i].szClassName == null || pdd_wx_infos[i].szClassName == "")
                    continue;
                ListViewItem lvi = new ListViewItem();
                lvi.Text = pdd_wx_infos[i].szWindowName;
                this.listView4.Items.Add(lvi);
            }
            this.listView4.EndUpdate();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Form2 form2 = new Form2();
            this.Hide();
            form2.Show();
        }
        //private void button2_Click(object sender, EventArgs e)
        //{
        //    DaTaoKe ke = new DaTaoKe();
        //    //richTextBox1.Text = ke.creat_taokouling("我推荐给你这个！", "https://uland.taobao.com/quan/detail?sellerId=2206563154962&activityId=99d0502de24c47d9aaebc5964b84d09e");
        //    //richTextBox1.Text = ke.parse_taokouling("￥42JlcerQ44e￥");
        //    TBKData data = ke.getSuggest();
        //    richTextBox1.Text = data.Wenan;
        //    richTextBox1.Text += "\n" + data.Tpwd;

        //    string kuanzhan = "https://dl028.kuaizhan.com/87/68/p651098661c309d?";
        //    kuanzhan = kuanzhan + "word="+ data.Tpwd.Replace("￥", "").Trim() + 
        //        "&image="+ System.Web.HttpUtility.UrlEncode(data.MarketingMainPic)+
        //        "&url=" + System.Web.HttpUtility.UrlEncode(data.CouponClickUrl);

        //    richTextBox1.Text += "\n"+shortUrl(kuanzhan);
        //}
    }
}
